from django.http import HttpResponse
import json
import requests
from bs4 import BeautifulSoup
import json

#返回结果格式
def resultData():
    data = {
        "websiteType" : 0,
        "titleName":"",
        "titleHref": "",
        "source":"",
        "label":"",
        "volume":"",
        "summary":"",
        "detailId":'',
        "publishTime" :"",
        "category" : "",
        "quote" :"",
        "abstract": "",
        "doi": "",
        "downLoad": "",
        "keyword": [],
        "author": [],

    }
    return data

def formData(response):
    allData = []

    lis = response['data']

    for item in lis:
        tempData = resultData()
        try:
            tempData["titleName"] = item['title'].strip();
        except:
            pass
        try:
            tempData["titleHref"] = 'http://www.1xuezhe.com/WeMedia/WeMediaContent?id='+str(item['id'])
        except:
            pass
        try:
            tempData["source"] = item['orgpdc']
        except:
            pass
        try:
            tempData["author"] = [item['name']]
        except:
            pass
        try:
            tempData["summary"] = item['contents']
        except:
            pass
        allData.append(tempData)

    return allData

def getData(keyword):
    headers = {
        'Proxy-Connection': 'keep-alive',
        'Pragma': 'no-cache',
        'Cache-Control': 'no-cache',
        'Proxy-Authorization': 'Basic cWY6cWYzLjE0MTU=',
        'Upgrade-Insecure-Requests': '1',
        'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36',
        'Accept': 'image/webp,image/apng,image/*,*/*;q=0.8',
        'Accept-Encoding': 'gzip, deflate',
        'Accept-Language': 'zh-CN,zh;q=0.9,en;q=0.8',
        'Referer': 'http://www.1xuezhe.com/WeMedia/SearchDoc?name=%E5%AD%A6%E6%9C%AF',
        'Origin': 'http://www.1xuezhe.com',
        'Content-Type': 'application/x-www-form-urlencoded',
        'X-Requested-With': 'XMLHttpRequest',
    }

    data = [
        ('page', '1'),
        ('rtn', '4'),
        ('alt', 'json'),
        ('name', keyword),
        ('type', '1'),
    ]

    response = requests.post('http://www.1xuezhe.com/WeMedia/GetWeMediaArticleListByName', headers=headers,data=data)

    allData = formData(response.json())

    return allData


def index(request):

    data = json.loads(request.POST.get('data', '1'))

    allData= getData(data["values"][0])

    return HttpResponse(json.dumps({
        "collection": allData,
        "allNum": 0
    }), content_type="application/json")